package com.spring.crm.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spring.crm.conf.CommonResult;
import com.spring.crm.conf.StringUtil;
import com.spring.crm.entity.ReimburseV;
import com.spring.crm.mapper.ReimburseVMapper;
import javafx.application.Application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * VIEW 前端控制器
 * </p>
 *
 * @author 何卓
 * @since 2022-02-10
 */
@RestController
@RequestMapping("/api/crm/reimburse-v")
public class ReimburseVController {
    private final static Logger LOGGER = LoggerFactory.getLogger(Application.class);
    @Resource
    private ReimburseVMapper reimburseVMapper;
    // 将 yml 中的自定义配置注入到这里
    @Value("${upload.path}")
    private String uploadPath;

    @CrossOrigin(origins = "*")
    @GetMapping("condition")
    public CommonResult selectByCondition(@CookieValue(value = "userAuth",defaultValue = "") String userAuth,@RequestParam Map<String,String> map) {
        CommonResult rs;
        try {
            String[] authArr = userAuth.split(",");
            if(!Arrays.asList(authArr).contains("a")){
                if(!map.containsKey("userId")){
                    return CommonResult.success("");
                }
            }
            QueryWrapper<ReimburseV> queryWrapper = new QueryWrapper<>();
            if(map.containsKey("reimburseId")){
                queryWrapper.eq("reimburse_id",map.get("reimburseId"));
            }
            if(map.containsKey("salesId")){
                queryWrapper.eq("sales_id",map.get("salesId"));
            }
            if(map.containsKey("realname")){
                queryWrapper.like("realname",map.get("realname"));
            }
            if(map.containsKey("reimburseStatus")){
                queryWrapper.eq("reimburse_status",map.get("reimburseStatus"));
            }
            if(map.containsKey("userId")){
                queryWrapper.eq("user_id",map.get("userId"));
            }
            queryWrapper.orderByDesc("create_time");
            Page<ReimburseV> page = new Page<>(Long.valueOf(map.get("current")),Long.valueOf(map.get("size")));
            IPage<ReimburseV> ReimburseIPage = reimburseVMapper.selectPage(page,queryWrapper);
            Integer selectCount = Math.toIntExact(reimburseVMapper.selectCount(queryWrapper));
            List<ReimburseV> list = ReimburseIPage.getRecords();
            rs = CommonResult.success(list,selectCount);
        }catch(Exception ex){
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }

    @CrossOrigin(origins = "*")
    @GetMapping("reminding")
    public CommonResult selectByReminding(@CookieValue(value = "userAuth",defaultValue = "") String userAuth,
                                          @CookieValue(value = "userId",defaultValue = "") String userId,
                                          @RequestParam Map<String,String> map) {
        CommonResult rs;
        try {
            String[] authArr = userAuth.split(",");
            if(!Arrays.asList(authArr).contains("a")){
                if(!map.containsKey("userId")){
                    map.put("userId",userId);
                }
            }
            QueryWrapper<ReimburseV> queryWrapper = new QueryWrapper<>();
            if(map.containsKey("reimburseId")){
                queryWrapper.eq("reimburse_id",map.get("reimburseId"));
            }
            if(map.containsKey("salesId")){
                queryWrapper.eq("sales_id",map.get("salesId"));
            }
            if(map.containsKey("realname")){
                queryWrapper.like("realname",map.get("realname"));
            }
            if(map.containsKey("reimburseStatus")){
                queryWrapper.eq("reimburse_status",map.get("reimburseStatus"));
            }
            if(map.containsKey("userId")){
                queryWrapper.eq("user_id",map.get("userId"));
            }
            queryWrapper.orderByDesc("create_time");
            Page<ReimburseV> page = new Page<>(Long.valueOf(map.get("current")),Long.valueOf(map.get("size")));
            IPage<ReimburseV> ReimburseIPage = reimburseVMapper.selectPage(page,queryWrapper);
            Integer selectCount = Math.toIntExact(reimburseVMapper.selectCount(queryWrapper));
            List<ReimburseV> list = ReimburseIPage.getRecords();
            rs = CommonResult.success(list,selectCount);
        }catch(Exception ex){
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }

    @CrossOrigin(origins = "*")
    @GetMapping("excel")
    public CommonResult selectByExcel(@CookieValue(value = "userAuth",defaultValue = "") String userAuth,@RequestParam Map<String,String> map) {
        CommonResult rs;
        try {
//            String[] authArr = userAuth.split(",");
//            if(!Arrays.asList(authArr).contains("a")){
//                if(!map.containsKey("userId")){
//                    return CommonResult.success("");
//                }
//            }
            QueryWrapper<ReimburseV> queryWrapper = new QueryWrapper<>();
            if(map.containsKey("reimburseId")){
                queryWrapper.eq("reimburse_id",map.get("reimburseId"));
            }
            if(map.containsKey("salesId")){
                queryWrapper.eq("sales_id",map.get("salesId"));
            }
            if(map.containsKey("realname")){
                queryWrapper.like("realname",map.get("realname"));
            }
            if(map.containsKey("reimburseStatus")){
                queryWrapper.eq("reimburse_status",map.get("reimburseStatus"));
            }
            if(map.containsKey("userId")){
                queryWrapper.eq("user_id",map.get("userId"));
            }
            queryWrapper.orderByDesc("create_time");
            Page<ReimburseV> page = new Page<>(Long.parseLong("1"),Long.parseLong("10000"));
            IPage<ReimburseV> ReimburseIPage = reimburseVMapper.selectPage(page,queryWrapper);
            Integer selectCount = Math.toIntExact(reimburseVMapper.selectCount(queryWrapper));
            List<ReimburseV> list = ReimburseIPage.getRecords();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String fileName = StringUtil.getUUID()+formatter.format(new Date())+"-reimburse.xlsx";
            String filePath = uploadPath+"attach/excel/";
            File dir = new File(filePath);
            if (!dir.exists()){
                boolean mkdirs = dir.mkdirs();
                if (!mkdirs) {
                    throw new Exception("创建目录失败!" + dir.getAbsolutePath());
                }
            }
            List<List<String>> listHead = new ArrayList<>();
            List<String> head0 = new ArrayList<>();
            head0.add("报销ID");
            List<String> head1 = new ArrayList<>();
            head1.add("");
            List<String> head2 = new ArrayList<>();
            head2.add("销售id");
            List<String> head3 = new ArrayList<>();
            head3.add("项目");
            List<String> head4 = new ArrayList<>();
            head4.add("用户id");
            List<String> head5 = new ArrayList<>();
            head5.add("姓名");
            List<String> head6 = new ArrayList<>();
            head6.add("金额");
            List<String> head7 = new ArrayList<>();
            head7.add("状态0-待审批1-已审批2-驳回");
            List<String> head8 = new ArrayList<>();
            head8.add("报销类型");
            List<String> head9 = new ArrayList<>();
            head9.add("说明");
            listHead.add(head0);
            listHead.add(head1);
            listHead.add(head2);
            listHead.add(head3);
            listHead.add(head4);
            listHead.add(head5);
            listHead.add(head6);
            listHead.add(head7);
            listHead.add(head8);
            listHead.add(head9);
            EasyExcel.write(filePath+fileName).head(listHead).sheet("报销").doWrite(list);
            rs = CommonResult.success("attach/excel/"+fileName);
        }catch(Exception ex){
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }
}
